<template>
  <div class="add-wrap" v-loading="loading">
    <Breadcrumb :titles="titles"></Breadcrumb>
    <BaseSectionInfo :baseInfo="baseInfo"></BaseSectionInfo>
    <div class="body">
      <div class="body-left">
        <div class="project">
          <el-form
            :model="basicForm"
            label-position="top"
            :rules="basicRules"
            ref="basicFormRef"
          >
            <!-- 基本信息 -->
            <div class="project-part">
              <div class="project-part-title">
                标段基础信息
              </div>

              <el-row>
                <el-col :span="8">
                  <el-form-item
                    label="标段名称(合同名称)"
                    prop="name"
                  >
                    <el-input
                      v-model="basicForm.name"
                      placeholder="请输入"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item
                    label="标段简称"
                    prop="simpleName"
                  >
                    <el-input
                      v-model="basicForm.simpleName"
                      placeholder="如：一标段，二标段"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item
                    label="合同金额(万元)"
                    prop="projectName"
                  >
                    <el-input
                      v-model="basicForm.money"
                      placeholder="请输入"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="8">
                  <el-form-item
                    label="负责单位"
                    prop="dutyUnit"
                  >
                    <!-- <el-select
                      placeholder="请选择"
                      v-model="basicForm.dutyUnit"
                      clearable
                      :disabled="isDetail"
                    >
                      <el-option
                        v-for="item in buildList"
                        :key="item.pkid"
                        :label="item.deptName"
                        :value="item.pkid"
                      >
                      </el-option>
                    </el-select> -->
                    <el-cascader
                      :options="responseOptions"
                      :props="{
                        checkStrictly: true,
                        emitPath: false,
                        value: 'deptName',
                        label: 'deptName',
                        children: 'childTree'
                      }"
                      v-model="basicForm.dutyUnit"
                      :disabled="isDetail"
                    ></el-cascader>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="建设阶段">
                    <el-radio-group
                      v-model="basicForm.stage"
                      :disabled="isDetail"
                    >
                      <el-radio label="前期"></el-radio>
                      <el-radio label="在建"></el-radio>
                      <el-radio label="完工"></el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item
                    label="标段效果图(按上传顺序，分别为点位1,2,3...)"
                  >
                    <el-upload
                      class="upload-image"
                      action=""
                      list-type="picture-card"
                      :auto-upload="false"
                      :on-change="handleChangeImage"
                      :on-remove="handleRemoveImage"
                      :on-preview="handlePreviewImage"
                      :show-file-list="true"
                      :file-list="fileList"
                      multiple
                      accept="image/*"
                    >
                      <i class="el-icon-plus"></i>
                    </el-upload>

                    <el-dialog
                      :visible.sync="previewVisible"
                      width="50%"
                    >
                      <img
                        :src="previewImage"
                        alt="预览"
                        style="width: 100%"
                      />
                    </el-dialog>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>

            <!-- 单位信息 -->
            <div class="project-part">
              <div class="project-part-title">单位信息</div>

              <el-row>
                <el-col :span="8">
                  <el-form-item label="建设单位名称">
                    <el-input
                      v-model="basicForm.buildUnitName"
                      placeholder="请输入"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="建设单位联系人">
                    <el-input
                      v-model="basicForm.buildUnitContract"
                      placeholder="请输入"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="建设单位联系方式">
                    <el-input
                      v-model="basicForm.buildUnitWay"
                      placeholder="请输入"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="8">
                  <el-form-item label="设计单位名称">
                    <el-input
                      v-model="basicForm.designUnitName"
                      placeholder="请输入"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="设计单位联系人">
                    <el-input
                      v-model="basicForm.designUnitContract"
                      placeholder="请输入"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="设计单位联系方式">
                    <el-input
                      v-model="basicForm.designUnitWay"
                      placeholder="请输入"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="8">
                  <el-form-item label="勘察单位名称">
                    <el-input
                      v-model="basicForm.surveyUnitName"
                      placeholder="请输入"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="勘察单位联系人">
                    <el-input
                      v-model="basicForm.surveyUnitContract"
                      placeholder="请输入"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="勘察单位联系方式">
                    <el-input
                      v-model="basicForm.surveyUnitWay"
                      placeholder="请输入"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="8">
                  <el-form-item label="施工单位名称">
                    <el-input
                      v-model="basicForm.workUnitName"
                      placeholder="请输入"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="施工单位联系人">
                    <el-input
                      v-model="basicForm.workUnitContract"
                      placeholder="请输入"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="施工单位联系方式">
                    <el-input
                      v-model="basicForm.workUnitWay"
                      placeholder="请输入"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="8">
                  <el-form-item label="监理单位名称">
                    <el-input
                      v-model="basicForm.supervisorUnitName"
                      placeholder="请输入"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="监理单位联系人">
                    <el-input
                      v-model="
                        basicForm.supervisorUnitContract
                      "
                      placeholder="请输入"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="监理单位联系方式">
                    <el-input
                      v-model="basicForm.supervisorUnitWay"
                      placeholder="请输入"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>

            <!-- 建设信息 -->
            <div class="project-part">
              <div class="project-part-title">建设信息</div>

              <el-row>
                <el-col :span="8">
                  <el-form-item label="红线面积(平方米)">
                    <el-input
                      v-model="basicForm.redArea"
                      placeholder="请输入"
                      type="number"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="总建筑面积(平方米)">
                    <el-input
                      v-model="basicForm.buildTotalArea"
                      placeholder="请输入"
                      type="number"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item
                    label="住宅面积（平方米）-含地下室"
                  >
                    <el-input
                      v-model="basicForm.residentialArea"
                      placeholder="请输入"
                      type="number"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="商业面积（平方米）">
                    <el-input
                      v-model="basicForm.commercialArea"
                      placeholder="请输入"
                      type="number"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item
                    label="社区综合体（平方米）"
                  >
                    <el-input
                      v-model="
                        basicForm.communityComplexArea
                      "
                      placeholder="请输入"
                      type="number"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="中学（平方米）">
                    <el-input
                      v-model="basicForm.middleSchoolArea"
                      placeholder="请输入"
                      type="number"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="小学（平方米）">
                    <el-input
                      v-model="basicForm.primarySchoolArea"
                      placeholder="请输入"
                      type="number"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="幼儿园（平方米）">
                    <el-input
                      v-model="basicForm.kindergartenArea"
                      placeholder="请输入"
                      type="number"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="房源套数(套)">
                    <el-input
                      v-model="basicForm.buildSourceCount"
                      placeholder="请输入"
                      type="number"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="8">
                  <el-form-item label="安置户数(户)">
                    <el-input
                      v-model="basicForm.households"
                      placeholder="请输入"
                      type="number"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="提供学位数(个)">
                    <el-input
                      v-model="basicForm.degrees"
                      placeholder="请输入"
                      type="number"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="机动车位数(个)">
                    <el-input
                      v-model="basicForm.carCount"
                      placeholder="请输入"
                      type="number"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="8">
                  <el-form-item
                    label="其中，充电桩个数(个)"
                  >
                    <el-input
                      v-model="basicForm.chargeCount"
                      placeholder="请输入"
                      type="number"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item
                    label="人防建筑面积(平方米)"
                  >
                    <el-input
                      v-model="basicForm.peopleBuildArea"
                      placeholder="请输入"
                      type="number"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item
                    label="海绵城市面积(平方米)"
                  >
                    <el-input
                      v-model="basicForm.cityArea"
                      placeholder="请输入"
                      type="number"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="8">
                  <el-form-item label="市政道路长度(公里)">
                    <el-input
                      v-model="basicForm.cityHallRoadLength"
                      placeholder="请输入"
                      type="number"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item
                    label="房建总平景观面积(平方米)"
                  >
                    <el-input
                      v-model="basicForm.buildSceneryArea"
                      placeholder="请输入"
                      type="number"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item
                    label="景观工程面积(平方米)"
                  >
                    <el-input
                      v-model="basicForm.sceneryArea"
                      placeholder="请输入"
                      type="number"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="8">
                  <el-form-item label="区域级绿道(公里)">
                    <el-input
                      v-model="basicForm.regionGreenRoad"
                      placeholder="请输入"
                      type="number"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="城市级绿道(公里)">
                    <el-input
                      v-model="basicForm.cityGreenRoad"
                      placeholder="请输入"
                      type="number"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="社区级绿道(公里)">
                    <el-input
                      v-model="basicForm.communityGreenRoad"
                      placeholder="请输入"
                      type="number"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="公园绿道(公里)">
                    <el-input
                      v-model="basicForm.parkGreenwayArea"
                      placeholder="请输入"
                      type="number"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <!-- </el-row>

              <el-row> -->
                <el-col :span="8">
                  <el-form-item
                    label="市政污水管道长度(公里)"
                  >
                    <el-input
                      v-model="
                        basicForm.sewagePipelineLength
                      "
                      placeholder="请输入"
                      type="number"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item
                    label="市政雨水管道长度(公里)"
                  >
                    <el-input
                      v-model="basicForm.outPipelineLength"
                      placeholder="请输入"
                      type="number"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item
                    label="市政给水管道长度(公里)"
                  >
                    <el-input
                      v-model="basicForm.inPipelineLength"
                      placeholder="请输入"
                      type="number"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <!-- </el-row>

              <el-row> -->
                <el-col :span="8">
                  <el-form-item
                    label="市政电力管道长度(公里)"
                  >
                    <el-input
                      v-model="
                        basicForm.electricPipelineLength
                      "
                      placeholder="请输入"
                      type="number"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item
                    label="市政燃气管道长度(公里)"
                  >
                    <el-input
                      v-model="basicForm.gasPipelineLength"
                      placeholder="请输入"
                      type="number"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item
                    label="市政综合管廊长度(公里)"
                  >
                    <el-input
                      v-model="
                        basicForm.synthesisPipelineLength
                      "
                      placeholder="请输入"
                      type="number"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <!-- </el-row>

              <el-row> -->
                <el-col :span="8">
                  <el-form-item
                    label="市政通信管道长度(公里)"
                  >
                    <el-input
                      v-model="
                        basicForm.communicationPipelineLength
                      "
                      placeholder="请输入"
                      type="number"
                      :disabled="isDetail"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-form>
        </div>
      </div>

      <div class="body-right">
        <!-- <div class="project-part">
          <div class="project-part-title top">推进节点</div>
          <AdvanceNode
            ref="advanceNodeRef"
            :stageList="stageList"
            :isDetail="isDetail"
          ></AdvanceNode>
        </div> -->
        <el-radio-group v-model="tabPosition" v-if="pkid">
          <el-radio-button label="node"
            >推进节点</el-radio-button
          >
          <el-radio-button label="info"
            >进度信息</el-radio-button
          >
        </el-radio-group>

        <div
          class="project-part"
          v-show="tabPosition === 'node'"
        >
          <div class="project-part-title top">推进节点</div>
          <AdvanceNode
            ref="advanceNodeRef"
            :stageList="stageList"
            :isDetail="isDetail"
          ></AdvanceNode>
        </div>

        <div
          class="project-part"
          v-show="tabPosition === 'info' && pkid"
        >
          <div class="project-part-title top">进度信息</div>

          <el-button
            icon="el-icon-plus"
            class="add-button"
            @click="addProcessInfo"
            >新增</el-button
          >
          <ProgressNodeInfo
            :isProgressEdit="isProgressEdit"
            :progressList="progressList"
            @edit="editProgress"
            @delete="deleteProgress"
          ></ProgressNodeInfo>
        </div>
      </div>
    </div>
    <div class="line" v-show="!isDetail">
      <el-button @click="saveInfo" class="save-btn"
        >保存</el-button
      >
    </div>

    <ProgressNodeDialog
      :visible.sync="showNodeDialog"
      :isEdit="isProgressDialogEdit"
      :effectList="effectList"
      :realList="realList"
      :currentData="currentData"
      title="项目进展信息"
      @confirm="handleSubmitProgress"
      @remove-uploaded="handleRemoveUploadedImage"
    />
  </div>
</template>

<script>
import Breadcrumb from '@/components/breadcrumb'
import AdvanceNode from '../components/advanceNode.vue'
import BaseSectionInfo from '../components/baseSectionInfo.vue'
import {
  querySectionInfo,
  addSectionInfo,
  uploadFileById,
  queryConstructionBaseInfo,
  queryNodeByType
} from '@/api/dataManagement'
import { sectionUnitOptions } from '@/utils/project/data'
import { STATIC_FILE_URL } from '@/api/config.js'
import dayjs from 'dayjs'
import { getDeptTree } from '@/api/dept'
import ProgressNodeInfo from '../components/progressNodeInfo.vue'
import ProgressNodeDialog from './components/addProgressNodeDialog.vue'
import { cloneDeep } from 'lodash'

export default {
  props: {
    pkid: String,
    title: String,
    projectId: String,
    isEdit: {
      type: Boolean,
      default: false
    },
    isDetail: {
      type: Boolean,
      default: false
    },
    type: String
  },
  components: {
    Breadcrumb,
    AdvanceNode,
    BaseSectionInfo,
    ProgressNodeInfo,
    ProgressNodeDialog
  },
  data() {
    return {
      basicForm: {
        // dutyUnit:
      },
      basicRules: {
        name: [
          {
            required: true,
            message: '请输入标段名称',
            trigger: 'blur'
          }
        ],
        simpleName: [
          {
            required: true,
            message: '请输入标段简称',
            trigger: 'blur'
          }
        ],
        money: [
          {
            required: true,
            message: '请输入合同金额',
            trigger: 'blur'
          }
        ]
        // dutyUnit: [
        //   {
        //     required: true,
        //     message: '请选择负责单位',
        //     trigger: 'blur'
        //   }
        // ]
      },
      loading: false,
      props: { multiple: true },
      fileList: [],
      dialogImageVisible: false,
      dialogImageUrl: '',
      sectionObj: {},
      stageList: [],
      progressList: [],
      uploadFileList: [],
      baseInfo: {},
      previewVisible: false,
      previewImage: '',
      advanceNodeRef: null,
      buildList: [],
      tabPosition: 'node',
      isProgressEdit: true,
      showNodeDialog: false,
      effectList: [],
      realList: [],
      isProgressDialogEdit: true,
      currentData: {},
      editIndex: -1,
      responseOptions: []
    }
  },
  computed: {
    titles() {
      return [this.title]
    },
    sectionUnitOptions() {
      return sectionUnitOptions
    },
    STATIC_FILE_URL() {
      return STATIC_FILE_URL
    }
  },
  watch: {},
  async mounted() {
    if (!this.pkid) {
      this.getNodeList()
    }
    await this.getBuildList()
    await this.getProjectInfo()
    if (this.pkid) {
      this.getDetailInfo()
    }
  },
  methods: {
    getNodeList() {
      queryNodeByType(this.type).then((res) => {
        if (res.success) {
          this.stageList = res.data
        }
      })
    },
    async getBuildList() {
      const res = await getDeptTree()
      if (res.success) {
        // this.buildList = res.data[0].childTree.filter(
        //   (i) => i.deptName === '建设公司'
        // )[0].childTree

        const target = res.data[0]
        if (target && target.childTree) {
          this.responseOptions = this.removeEmptyChildTree(
            target.childTree
          )
        } else {
          this.responseOptions = []
        }
      }
    },
    removeEmptyChildTree(nodes) {
      return nodes
        .map((node) => {
          if (Array.isArray(node.childTree)) {
            node.childTree = this.removeEmptyChildTree(
              node.childTree
            )
            if (node.childTree.length === 0) {
              delete node.childTree
            }
          }
          return node
        })
        .filter((node) => {
          return (
            !node.childTree ||
            (Array.isArray(node.childTree) &&
              node.childTree.length > 0)
          )
        })
    },
    getProjectInfo() {
      queryConstructionBaseInfo(this.projectId).then(
        (res) => {
          if (res.success) {
            if (res.data) {
              this.baseInfo = res.data.baseMess
            }
          }
        }
      )
    },
    getDetailInfo() {
      this.loading = true
      querySectionInfo(this.pkid).then((res) => {
        if (res.success) {
          this.sectionObj = res.data
          this.basicForm = res.data.section
          this.stageList = res.data.node
          this.progressList = res.data.process
          // if (res.data.section.dutyUnit) {
          //   this.basicForm.dutyUnit =
          //     res.data.section.dutyUnit.split(',')
          // } else {
          //   this.basicForm.dutyUnit = []
          // }
          if (
            res.data.sectionEffectPictureIds &&
            res.data.sectionEffectPictureIds.length
          ) {
            this.fileList =
              res.data.sectionEffectPictureIds.map(
                (item) => {
                  return {
                    ...item,
                    url: `${STATIC_FILE_URL}${item.filePath}`
                  }
                }
              )
            this.uploadFileList = JSON.parse(
              JSON.stringify(this.fileList)
            )
          }
        }
        this.loading = false
      })
    },

    handleSubmitProgress(form, imageList, uploadList) {
      const isEdit = this.editIndex > -1

      // 构建最终的progressPictureIds：合并保留的已上传图片和新上传的图片信息
      let finalProgressPictureIds = []

      // 1. 先添加删除后保留的已上传图片
      if (uploadList !== undefined && uploadList !== null) {
        finalProgressPictureIds = uploadList
      } else {
        // 2. 如果没有传入uploadList，使用原有的progressPictureIds
        finalProgressPictureIds =
          form.progressPictureIds || []
      }

      const progressItem = {
        ...form,
        createTime: isEdit
          ? this.progressList[this.editIndex].createTime ||
            dayjs().format('YYYY-MM-DD')
          : dayjs().format('YYYY-MM-DD'),
        imageArr: imageList,
        progressPictureIds: finalProgressPictureIds
      }

      if (isEdit) {
        const newItem = {
          ...this.progressList[this.editIndex],
          ...progressItem
        }
        this.$set(
          this.progressList,
          this.editIndex,
          newItem
        )
      } else {
        this.progressList.unshift(progressItem)
      }

      this.showNodeDialog = false
    },

    handleRemoveUploadedImage(file) {
      // 1. 更新realList，移除删除的图片
      const beforeCount = this.realList.length

      this.realList = this.realList.filter((item) => {
        const shouldRemove =
          (item.fileId && item.fileId === file.fileId) ||
          (item.pkid && item.pkid === file.pkid) ||
          (item.filePath && item.filePath === file.filePath)

        if (shouldRemove) {
        }

        return !shouldRemove
      })

      const afterCount = this.realList.length

      // 2. 同步更新当前编辑项的progressPictureIds - 使用更彻底的更新方式
      if (this.editIndex > -1) {
        const currentItem =
          this.progressList[this.editIndex]
        if (currentItem.progressPictureIds) {
          const originalLength =
            currentItem.progressPictureIds.length

          // 创建新的progressPictureIds数组
          const newProgressPictureIds =
            currentItem.progressPictureIds.filter(
              (item) => {
                const shouldRemove =
                  (item.fileId &&
                    item.fileId === file.fileId) ||
                  (item.pkid && item.pkid === file.pkid) ||
                  (item.filePath &&
                    item.filePath === file.filePath)

                if (shouldRemove) {
                }

                return !shouldRemove
              }
            )

          // 创建完全新的item对象
          const newItem = {
            ...currentItem,
            progressPictureIds: newProgressPictureIds
          }

          // 使用$set替换整个item
          this.$set(
            this.progressList,
            this.editIndex,
            newItem
          )

          this.$nextTick(() => {})
        }
      }
    },

    editProgress(item, index) {
      this.editIndex = index
      this.currentData = cloneDeep(item)

      // 处理效果图列表
      this.effectList = this.uploadFileList.map(
        (uploadItem) => {
          if (uploadItem.pkid) {
            return {
              src: `${STATIC_FILE_URL}${uploadItem.filePath}`,
              filePath: uploadItem.filePath,
              pkid: uploadItem.pkid,
              isUploaded: true
            }
          } else {
            return {
              src: URL.createObjectURL(uploadItem),
              filePath: uploadItem.name,
              isUploaded: false,
              file: uploadItem
            }
          }
        }
      )

      // 使用深拷贝的数据来避免修改原始对象
      const itemCopy = cloneDeep(item)

      // 确保progressPictureIds和imageArr都是数组
      if (!itemCopy.progressPictureIds) {
        itemCopy.progressPictureIds = []
      }
      if (!itemCopy.imageArr) {
        itemCopy.imageArr = []
      }

      // 构建实景图列表，合并已上传图片和本地文件
      this.realList = []

      // 添加已上传的图片
      if (
        itemCopy.progressPictureIds &&
        itemCopy.progressPictureIds.length > 0
      ) {
        const uploadedPics =
          itemCopy.progressPictureIds.map((pic) => ({
            ...pic,
            pkid: pic.pkid || pic.fileId,
            fileId: pic.fileId || pic.pkid,
            filePath: pic.filePath,
            // 确保有这些关键属性供删除时匹配
            name:
              pic.filePath || pic.name || 'uploaded-image'
          }))

        this.realList = this.realList.concat(uploadedPics)
      }

      // 添加本地文件
      if (
        itemCopy.imageArr &&
        itemCopy.imageArr.length > 0
      ) {
        const localFiles = itemCopy.imageArr.filter(
          (file) => file instanceof File
        )
        this.realList = this.realList.concat(localFiles)
      }

      this.showNodeDialog = true
    },

    deleteProgress(index) {
      this.progressList.splice(index, 1)
    },

    saveInfo() {
      this.$refs.basicFormRef.validate((valid) => {
        if (!valid) return
        this.loading = true
        // if (this.basicForm.dutyUnit) {
        //   this.basicForm.dutyUnit =
        //     this.basicForm.dutyUnit.join(',')
        // } else {
        //   this.basicForm.dutyUnit = ''
        // }
        const section = this.basicForm

        const newMainImages = this.uploadFileList.filter(
          (f) => !f.pkid
        )
        const existingMainImages =
          this.uploadFileList.filter((f) => f.pkid)

        const uploadMainImageTasks = newMainImages.map(
          (file) => {
            const formData = new FormData()
            formData.append('file', file.raw || file)
            return uploadFileById(formData)
          }
        )

        const progressUploadTasks = this.progressList.map(
          (item, index) => {
            const rawImageList = (
              item.imageArr || []
            ).filter((img) => img)
            const uploadTasks = rawImageList.map(
              (file, i) => {
                const realFile =
                  file.rawFile || file.raw || file
                const formData = new FormData()
                formData.append('file', realFile)
                return uploadFileById(formData).then(
                  (res) => {
                    if (res.success) {
                      return {
                        fileId: res.data,
                        orderIndex: i
                      }
                    } else {
                      throw new Error(
                        `第 ${
                          index + 1
                        } 条进度的图片上传失败`
                      )
                    }
                  }
                )
              }
            )

            return Promise.all(uploadTasks).then(
              (uploadedImages) => {
                const existingImages =
                  item.progressPictureIds || []
                return {
                  ...item,
                  progressPictureIds:
                    existingImages.concat(uploadedImages),
                  imageArr: undefined
                }
              }
            )
          }
        )

        Promise.all([
          Promise.all(uploadMainImageTasks),
          Promise.all(progressUploadTasks)
        ])
          .then(
            ([
              mainUploadResults,
              processedProgressList
            ]) => {
              const allMainSuccess =
                mainUploadResults.every(
                  (res) => res.success
                )
              if (!allMainSuccess) {
                this.$message.error(
                  '主页面部分图片上传失败'
                )
                return
              }

              this.progressList = processedProgressList

              const sectionEffectPictureIds = [
                ...existingMainImages.map((img, i) => ({
                  fileId: img.fileId,
                  pkid: img.pkid,
                  orderIndex: i
                })),
                ...mainUploadResults.map((res, i) => ({
                  fileId: res.data,
                  orderIndex: existingMainImages.length + i
                }))
              ]

              const node = this.$refs.advanceNodeRef
                .getStageList()
                .map((item) => ({
                  ...item,
                  planStartTime: item.planStartTime
                    ? dayjs(item.planStartTime).format(
                        'YYYY-MM-DD'
                      )
                    : '',
                  planEndTime: item.planEndTime
                    ? dayjs(item.planEndTime).format(
                        'YYYY-MM-DD'
                      )
                    : '',
                  actuallyTime: item.actuallyTime
                    ? dayjs(item.actuallyTime).format(
                        'YYYY-MM-DD'
                      )
                    : ''
                }))

              const params = {
                projectId: this.projectId,
                section,
                node,
                process: processedProgressList,
                sectionEffectPictureIds
              }

              return addSectionInfo(params)
            }
          )
          .then((res) => {
            if (res && res.success) {
              this.$message.success('保存成功')
              this.$router.push({
                path: '/dataManagement/projectManagement/sectionManagement/list',
                query: { refresh: Date.now() }
              })
            } else if (res) {
              this.$message.error(res.message || '保存失败')
            }
            this.loading = false
          })
          .catch(() => {
            this.$message.error('图片上传出错，请稍后再试')
            this.loading = false
          })
      })
    },

    handleSubmit(data) {
      console.log('提交进度数据:', data)
    },

    handleRemoveImage(file) {
      file.name
        ? (this.uploadFileList = this.uploadFileList.filter(
            (i) => i.name !== file.name
          ))
        : (this.uploadFileList = this.uploadFileList.filter(
            (i) => i.url !== file.url
          ))
    },

    handleChangeImage(file, fileList) {
      this.uploadFileList.push(file.raw)
    },

    handlePreviewImage(file) {
      if (file.url) {
        this.previewImage = file.url
      } else if (file.raw) {
        this.previewImage = URL.createObjectURL(file.raw)
      }
      this.previewVisible = true
    },

    addProcessInfo() {
      this.editIndex = -1
      this.currentData = {
        stageRemark: '',
        problemDescription: '',
        hasProblem: '否'
      }
      this.showNodeDialog = true
      this.isProgressDialogEdit = false

      // 处理效果图列表，统一数据格式
      this.effectList = this.uploadFileList.map((item) => {
        if (item.pkid) {
          return {
            src: `${STATIC_FILE_URL}${item.filePath}`,
            filePath: item.filePath,
            pkid: item.pkid,
            isUploaded: true
          }
        } else {
          return {
            src: URL.createObjectURL(item),
            filePath: item.name,
            isUploaded: false,
            file: item
          }
        }
      })

      // 新增时清空实景图列表
      this.realList = []
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/form.scss';
.add-wrap {
  padding: 0 20px;

  .body {
    display: flex;
    padding: 10px 0 0 10px;

    &-left {
      width: 70%;
      border-right: 1px solid #f1f1f1;
      overflow: scroll;
    }

    &-right {
      flex: 1;
      padding-left: 10px;
      overflow-y: auto;
    }

    .top {
      display: flex;
      justify-content: space-between;
      align-items: baseline;
      padding-right: 10px;
    }
  }

  .line {
    display: flex;
    justify-content: center;
  }

  .top {
    margin-top: 20px;
  }
}

::v-deep .el-upload-list__item-status-label {
  display: none !important;
}

.project-part {
  position: relative;

  .add-button {
    position: absolute;
    right: 0;
    top: 0;
    width: 100px;
    height: 32px;
    background: #497fa3;
    border-radius: 4px;
    color: #fff;
    font-size: 14px;
    font-weight: 400;
    margin-left: 150px;
    margin-top: -8px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
